package tech.summerly.weather.component.adapter

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item_life_style.view.*
import tech.summerly.weather.R
import tech.summerly.weather.data.bean.DailyForecast
import tech.summerly.weather.util.ViewHolder
import tech.summerly.weather.util.string


class LifeStyleAdapter : RecyclerView.Adapter<ViewHolder>() {

    companion object {

        const val TODAY = 0

        private val DRAWABLES = listOf(
                R.drawable.ic_dress,
                R.drawable.ic_medical,
                R.drawable.ic_sun,
                R.drawable.ic_local_car_wash_black_24dp
        )

    }

    private var forecast: DailyForecast? = null

    private var day: Int = TODAY

    /**
     * @param forecast data source
     * @param day to show which day'life style
     */
    fun setData(forecast: DailyForecast, day: Int = TODAY) {
        this.forecast = forecast
        this.day = day
        notifyDataSetChanged()
    }

    private val getDescription: (Int) -> String = { position: Int ->
        val forecast = this@LifeStyleAdapter.forecast
        if (forecast == null) {
            throw IllegalStateException("forecast is null")
        }
        when (position) {
            0 -> {
                string(R.string.template_dressing, forecast.dressing[day].desc)
            }
            1 -> {
                string(R.string.template_cold_risk, forecast.coldRisk[day].desc)
            }
            2 -> {
                string(R.string.template_ultraviolet, forecast.ultraviolet[day].desc)
            }
            3 -> {
                string(R.string.template_car_wash, forecast.carWashing[day].desc)
            }
            else -> "错误参数：$position"
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(R.layout.item_life_style, parent, LayoutInflater.from(parent.context))
    }

    override fun getItemCount(): Int = if (forecast == null) 0 else 4

    override fun onBindViewHolder(holder: ViewHolder, position: Int) = with(holder.itemView) {
        icon.setImageResource(DRAWABLES[position])
        textDesc.text = getDescription(position)
    }
}
